﻿#include "LeiJiaGameStart.h"
#include "LeiJiaWebHttp.h"
#include <QTextBlockFormat>
#include <QTextCodec>
#include <QTimer>
#include <QFileInfo>
#include "Information.h"
#include "LeiJiaLoadingGifDialog.h"

LeiJiaGameStart::LeiJiaGameStart(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	ui.label_GameProfiles->setWordWrap(true);
	m_gameResult = NULL;
	isStart = false;
	dlg = new LeiJiaLoadingGifDialog();
	thread = new myThread;
	connect(thread, SIGNAL(finished()), this, SLOT(slot_threadFinished()));
	connect(thread, SIGNAL(signal_waitFailed()), this, SLOT(slot_waitFailed()));

	connect(ui.btl_back, SIGNAL(clicked()), this, SLOT(slot_back()));
	connect(ui.m_pBtn_Start_Kill, SIGNAL(clicked()), this, SLOT(slot_Start_Kill()));
	connect(LeiJiaWebHttp::GetInstance(), SIGNAL(signal_addPlayTime()), this, SLOT(slot_addPlayTime()));
	connect(LeiJiaWebHttp::GetInstance(), SIGNAL(signal_globalTime(int)), this, SLOT(slot_timeOut(int)));
	connect(ui.m_btlAddTime, SIGNAL(clicked()), this, SLOT(slot_btlAddTime()));

	QString style = QString(" QPushButton#m_pBtn_Start_Kill{border-image:url(%1);} ").arg(LeiJiaWebHttp::GetInstance()->startImage);
	ui.m_pBtn_Start_Kill->setStyleSheet(style);

	style = QString(" QWidget#m_widget{border-image:url(%1);} ").arg(LeiJiaWebHttp::GetInstance()->backGroundImage);
	ui.m_widget->setStyleSheet(style);

	style = QString(" QWidget#widget_h{border-image:url(%1);} ").arg(LeiJiaWebHttp::GetInstance()->Image);
	ui.widget_h->setStyleSheet(style);

	style = QString(" QWidget#widget_h2{border-image:url(%1);} ").arg(LeiJiaWebHttp::GetInstance()->Image);
	ui.widget_h2->setStyleSheet(style);
	
	style = QString(" QWidget#widget_h3{border-image:url(%1);} ").arg(LeiJiaWebHttp::GetInstance()->Image);
	ui.widget_h3->setStyleSheet(style);

	style = QString(" QWidget#widget_head{border-image:url(%1);} ").arg(LeiJiaWebHttp::GetInstance()->headImage);
	ui.widget_head->setStyleSheet(style);

	style = QString(" QWidget#widget_bottom{border-image:url(%1);} ").arg(LeiJiaWebHttp::GetInstance()->GameschildBackImage);

	ui.widget_bottom->setStyleSheet(style);

	style = QString(" QWidget#widget_time{border-image:url(%1);} ").arg(LeiJiaWebHttp::GetInstance()->timeDispImage2);
	ui.widget_time->setStyleSheet(style);

	style = QString(" QPushButton#btl_back{border-image:url(%1); background-color:transparent;} ").arg(LeiJiaWebHttp::GetInstance()->lastPageImage);
	ui.btl_back->setStyleSheet(style);

	style = QString(" QWidget#widget_middle{border-image:url(%1); background-color:transparent;} ").arg(LeiJiaWebHttp::GetInstance()->GameschildBackImage);
	ui.widget_middle->setStyleSheet(style);
	
	style = QString(" QPushButton{border-image:url(%1);} ").arg(LeiJiaWebHttp::GetInstance()->btlAddTimeImage);
	ui.m_btlAddTime->setStyleSheet(style);
	//ui.m_btlAddTime->hide();
}	

LeiJiaGameStart::~LeiJiaGameStart()
{
	if (dlg)
		delete dlg;
	dlg = NULL;
	if (thread)
		delete thread;
	thread = NULL;
}
void LeiJiaGameStart::slot_btlAddTime()// 续费按钮
{
	LeiJiaWebHttp::GetInstance()->btlAddTime();
}
void LeiJiaGameStart::setTimeSecs(int secs, QDateTime currentTime)
{
	m_secs = secs;
	m_currentTime = currentTime;
	m_endToTime = currentTime.addSecs(m_secs);
	if (secs == 0)
	{
		ui.label_time->setText("00:00");
		return;
	}
	/*else
	{
		m_timer->start(0);
	}*/
}
void LeiJiaGameStart::slot_threadFinished()//线程结束信号
{
	QString style = QString(" QPushButton#m_pBtn_Start_Kill{border-image:url(%1);} ").arg(LeiJiaWebHttp::GetInstance()->endImage);
	dlg->setMoviePaused(true);
	QString strUrl = LeiJiaWebHttp::GetInstance()->touchWebUrl + "/log/WriteGameOperationLog";
	if (isStart)
	{
		ui.m_pBtn_Start_Kill->setStyleSheet(style);
		QByteArray byte_array = LeiJiaWebHttp::GetInstance()->GameOperationLog(m_gameResult->GameId, 0, m_guid);
		LeiJiaWebHttp::GetInstance()->PostByUrl(strUrl, byte_array, postEnum::enumWriteGame);
		m_gameResult->playCount++;
		LeiJiaWebHttp::GetInstance()->updatePlayCount(m_gameResult->GameName);
	}
	else
	{
		style = QString(" QPushButton#m_pBtn_Start_Kill{border-image:url(%1);} ").arg(LeiJiaWebHttp::GetInstance()->startImage);
		ui.m_pBtn_Start_Kill->setStyleSheet(style);

		QString text = QString::fromLocal8Bit("游戏启动失败！！！");
		dlg->setLabelText(text);
	}
	//等待10秒钟
	QTime dieTime = QTime::currentTime().addSecs(5);
	while (QTime::currentTime() < dieTime)
	{
		QCoreApplication::processEvents(QEventLoop::AllEvents, 100);//使程序保持响应
	}
	dlg->hide();
	this->raise();// 窗体置顶
	this->activateWindow();// 设置当前窗体为活动窗体
	this->setFocus();

	ui.m_pBtn_Start_Kill->setEnabled(true);
}
void LeiJiaGameStart::slot_waitFailed()// 游戏启动失败
{
	isStart = false;
}
void LeiJiaGameStart::slot_addPlayTime()
{
	QDateTime currentTime = QDateTime::currentDateTime();
	int timeSecs = LeiJiaWebHttp::GetInstance()->getPlayValue() * 60;//获取游戏时间
	int last = currentTime.secsTo(m_endToTime);
	m_endToTime = currentTime.addSecs(timeSecs+last);
}
void LeiJiaGameStart::slot_back()// 返回按钮
{
	if (isStart)
	{
		Information info;
		QString message = QString::fromLocal8Bit("您已在一个游戏运行中，需关闭当前游戏后开启其他游戏");
		QString style = QString("QDialog{border-image:url(%1); } QPushButton{border-image:url(%2);}QPushButton:pressed{ border-image:url(%3);} ").arg(LeiJiaWebHttp::GetInstance()->loadingImage).arg(LeiJiaWebHttp::GetInstance()->iKonwButtonImage).arg(LeiJiaWebHttp::GetInstance()->iKonwButtonStateImage);
		info.setLabelText(message, style);
		info.exec();
	}
	else
	{
		if (LeiJiaWebHttp::GetInstance()->playVideo)
		{
			LeiJiaWebHttp::GetInstance()->gameResultDetail(NULL, 0);
			LeiJiaWebHttp::GetInstance()->setHomePlayVolume(50); // 设置游戏首页视频音量
		}
		else
		{
			LeiJiaWebHttp::GetInstance()->gameResultDetail(NULL, 1);
		}
	}
}
void LeiJiaGameStart::slot_timeOut(int secs)
{
	int m = (secs ) / 60;
	int s = (secs) % 60;
	QString strm = QString::number(m);
	QString strs = QString::number(s);
	if (m <= 9)
	{
		strm = "0" + strm;
	}
	if (s <= 9)
	{
		strs = "0" + strs;
	}
	QString disp = strm + QString::fromLocal8Bit(":") + strs;
	ui.label_time->setText(disp);
	//if (m < 5)
	//{
	//	ui.m_btlAddTime->show();
	//}
	//else
	//{
	//	ui.m_btlAddTime->hide();
	//}
	if (secs == 0)
	{
		isStart = true;
		ui.m_btlAddTime->hide();
		emit  tiemEnd();
		if (m_gameResult == NULL)
		{
			return;
		}
		slot_Start_Kill();
		return;
	}
}
void LeiJiaGameStart::setGameName(QString name)
{
	m_gameName = m_gameResult->GameName;
}
void LeiJiaGameStart::slot_Start_Kill()
{
	QString strUrl = LeiJiaWebHttp::GetInstance()->touchWebUrl + "/log/WriteGameOperationLog";
	if (m_gameResult == NULL)
		return;
	LeiJiaWebHttp::GetInstance()->writeLog(m_gameResult->GameName);
	if (!isStart)
	{
		//<游戏启动，提示玩家	
		QString text = QString::fromLocal8Bit("游戏正在启动中，请在工作人员的指导下，戴上虚拟现实头盔！！！");
		dlg->setLabelText(text);
		dlg->startGif();
		dlg->show();
		//ui.btl_back->setEnabled(false);//游戏未结束不能返回
		ui.m_pBtn_Start_Kill->setEnabled(false);//设置按钮失效，防止启动游戏过程中再次点击
		isStart = true;	
		//<设置按钮启动等待样式
		QString style = QString(" QPushButton#m_pBtn_Start_Kill{border-image:url(%1);} ").arg(LeiJiaWebHttp::GetInstance()->loadGameImage);
		ui.m_pBtn_Start_Kill->setStyleSheet(style);
		QString startPath = m_gameResult->GamePath;
		LeiJiaWebHttp::GetInstance()->writeLog("start.......");
		LeiJiaWebHttp::GetInstance()->writeLog(startPath);
		QByteArray ba = startPath.toLocal8Bit();
	    char* c_starPath =ba.data();
		//启动游戏任务线程
		QString name = getNameByPath(startPath);//通过游戏路径获取进程名称
		thread->setData(c_starPath, *m_gameResult);
		thread->setGameName(name);
		thread->start();	
		style = QString(" QPushButton#m_pBtn_Start_Kill{border-image:url(%1);} ").arg(LeiJiaWebHttp::GetInstance()->endImage);
		ui.m_pBtn_Start_Kill->setStyleSheet(style);
	}
	else if (isStart)
	{
		isStart = false;
		QString style ;
		QString startPath = m_gameResult->GamePath;//启动游戏路径
		QString name =getNameByPath(startPath);//通过游戏路径获取进程名称
		QString lowerName = name.toLower();// 将名称转成小写
		style = QString(" QPushButton#m_pBtn_Start_Kill{border-image:url(%1);} ").arg(LeiJiaWebHttp::GetInstance()->startImage);
		ui.m_pBtn_Start_Kill->setStyleSheet(style);
		QByteArray byte_array = LeiJiaWebHttp::GetInstance()->GameOperationLog(m_gameResult->GameId, 1, m_guid);
		LeiJiaWebHttp::GetInstance()->PostByUrl(strUrl, byte_array, postEnum::enumWriteGame);

		if (lowerName.isEmpty())
		{
			return;
		}	
		LeiJiaWebHttp::GetInstance()->writeLog(lowerName);
		QByteArray ba = lowerName.toLocal8Bit();
		char* c_starPath = ba.data();
		DLLTaskKill(c_starPath);//关闭游戏进程
		QStringList list = LeiJiaWebHttp::GetInstance()->getSpecialGamesList();
		for (int i = 0; i < list.count(); i++)
		{
			LeiJiaWebHttp::GetInstance()->writeLog(list.at(i));
			QString name = list.at(i).toLower();
			if (name.isEmpty())
			{
				break;
			}
			QByteArray ba = name.toLocal8Bit();
			char* c_starPath = ba.data();
			DLLTaskKill(c_starPath);//关闭特殊游戏进程
		}
		QString appPath = "gameinfo";
		QByteArray arry = appPath.toLocal8Bit();
		char* cPath = arry.data();
		DLLTaskKill(cPath);//关闭特殊游戏进程
	}
}

void LeiJiaGameStart::setGameInfo(GameResult *result)//设置游戏信息
{
	//m_gameResult = { 0 };
	m_gameResult = result;
	initGameUi();
}
void LeiJiaGameStart::initGameUi()
{
	m_guid = LeiJiaWebHttp::GetInstance()->createGuid();
	QString appPath = QApplication::applicationDirPath()+"/image/";
	if (m_gameResult->listBigImages.count() > 0)
	{//<设置游戏大图
		QString style = QString("QWidget#widget_gameImage{border-image:url(%0);border-radius: 15px;border: 2px solid;}").arg(appPath+m_gameResult->listBigImages.at(0).ImageUrl);
		ui.widget_gameImage->setStyleSheet(style);
	}
	QString myString;//设置行高为28px 
	myString.append("<p style='line-height:28px;'>");
	myString.append(m_gameResult->GameProfiles);
	myString.append("</p>");
	ui.textBrowser->setText(myString);
	ui.label_gameName->setText(m_gameResult->GameName);//设置游戏名称
	QString typesName;
	for (int i = 0; i < m_gameResult->listType.count(); i++)
	{
			GameTypes type = m_gameResult->listType.at(i);
			typesName = typesName + type.Name + "  ";	
	}
	ui.label_types->setText(typesName);//设置游戏类型
	//< 设置游戏截图
	for (int i = 0; i < m_gameResult->listIntroduceImages.count(); i++)
	{
		Images image = m_gameResult->listIntroduceImages.at(i);
		QString str = QString("QLabel{border-image:url(%0);}").arg(appPath+image.ImageUrl);
		//LeiJiaWebHttp::GetInstance()->writeLog(image.ImageUrl);
		if (i == 0)
		{
			ui.label->setStyleSheet(str);
		}
		if (i == 1)
		{
			ui.label_2->setStyleSheet(str);
		}
		if (i == 2)
		{
			ui.label_3->setStyleSheet(str);
		}
	}
	QString str = QString("QWidget{border-image:url(%0);}").arg(appPath);
	ui.widget_13->setStyleSheet(str);
	ui.widget_14->setStyleSheet(str);
	//<设置游戏操作图片
	for (int i = 0; i < m_gameResult->listOperationImages.count(); i++)
	{
		Images image = m_gameResult->listOperationImages.at(i);
		QString str = QString("QWidget{border-image:url(%0);}").arg(appPath+image.ImageUrl);
		if (i == 0)
		{
			ui.widget_13->setStyleSheet(str);
		}
		if (i == 1)
		{
	     	ui.widget_14->setStyleSheet(str);
		}
	}
}
QString LeiJiaGameStart::getNameByPath(QString& path)
{
	QFileInfo fIno(path);
	QString name = fIno.fileName();
	name = name.left(name.length() - 4);//去掉.exe
	LeiJiaWebHttp::GetInstance()->writeLog(name);
	return name;
}
void   LeiJiaGameStart::DLLTaskKill(char* cname)
{
	int ID = 0;
	//进程列举  
	printf("%s\n", cname);
	std::string name(cname);
	const char *cPath = name.c_str();
	printf("%s\n", cPath);
	HANDLE hSnApshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hSnApshot != INVALID_HANDLE_VALUE)
	{
		PROCESSENTRY32 te = { sizeof(te) };
		BOOL f0k = Process32First(hSnApshot, &te);
		for (; f0k; f0k = Process32Next(hSnApshot, &te))
		{
			wprintf(L"Pid: %d %s\n", te.th32ProcessID, te.szExeFile);
			int size = WideCharToMultiByte(CP_ACP, 0, te.szExeFile, -1, NULL, 0, NULL, NULL);
			char *ch = new char[size + 1];
			
			if (WideCharToMultiByte(CP_ACP, 0, te.szExeFile, -1, ch, size, NULL, NULL))
			{
				_strlwr_s(ch, strlen(ch) + 1); // 将进程名称转换成小写
				if (strstr(ch, cPath))//。
				{
					ID = te.th32ProcessID;
					HANDLE hProcess;
					// 现在我们用函数 TerminateProcess()终止进程：
					// 这里我们用PROCESS_ALL_ACCESS
					hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, ID);
					TerminateProcess(hProcess, 0);
					CloseHandle(hProcess);
				}
			}
		}
	}
	CloseHandle(hSnApshot);
}

